package cn.yy.cm.config;

import com.sun.istack.internal.NotNull;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.filter.TypeFilter;

import java.io.IOException;
import java.util.Map;

/**
 * 描述: 注解导入BeanDefinition注册bean
 *
 * @author: yanglin
 * @Date: 2021-11-29-10:13
 * @Version: 1.0
 */
public class DImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry, BeanNameGenerator importBeanNameGenerator) {

        // 根据注解得到扫描包路径
        Map<String, Object> annotationAttributes = importingClassMetadata.getAnnotationAttributes(DMapperScan.class.getName());
        String scanPath = (String) annotationAttributes.get("value");

        // 设置Spring扫描IncludeFilter为true;不验证注解Component
        DBeanDefinitionScanner beanDefinitionScanner = new DBeanDefinitionScanner(registry);

        // 设置beanDefinitionScanner不验证Include;(默认是判断有无@Component)
        beanDefinitionScanner.addIncludeFilter(new TypeFilter() {
            @Override
            public boolean match(@NotNull MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
                return true;
            }
        });

        // 执行扫描
        beanDefinitionScanner.scan(scanPath);
    }
}
